package com.example.mqttclient;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.example.mqttclient.mqtt.MqttService;

import org.eclipse.paho.client.mqttv3.MqttException;

// MainActivity类，继承自AppCompatActivity，并实现MqttService.MqttEventCallBack接口
public class MainActivity extends AppCompatActivity implements MqttService.MqttEventCallBack {
    // 用于显示连接状态的TextView
    private TextView connectState;
    // MqttService的绑定对象，通过它可以调用MqttService中的方法
    private MqttService.MqttBinder mqttBinder;
    // 用于日志记录的标签
    private String TAG = "MainActivity";
    // 定义ServiceConnection，用于监听MqttService服务的连接和断开
    private ServiceConnection connection = new ServiceConnection() {
        // 当服务连接成功时调用
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            // 将传入的IBinder转换为MqttService.MqttBinder
            mqttBinder = (MqttService.MqttBinder) iBinder;
            // 设置MqttService的事件回调对象为当前MainActivity
            mqttBinder.setMqttEventCallback(MainActivity.this);
            // 判断MqttService是否已连接
            if (mqttBinder.isConnected()) {
                // 已连接，更新连接状态显示为“已连接”
                connectState.setText("已连接");
                // 订阅主题
                subscribeTopics();
            } else {
                // 未连接，更新连接状态显示为“未连接”
                connectState.setText("未连接");
            }
        }

        // 当服务断开连接时调用
        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            // 此处暂时不做处理
        }
    };

    // 当Activity创建时调用
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 设置Activity的布局为activity_main
        setContentView(R.layout.activity_main);
        // 通过findViewById获取布局文件中id为connect_state的TextView
        connectState = findViewById(R.id.connect_state);
        // 创建启动MqttService服务的Intent
        Intent mgttServiceIntent = new Intent(this, MqttService.class);
        // 绑定MqttService服务，BIND_AUTO_CREATE表示如果服务未运行则自动创建
        bindService(mgttServiceIntent, connection, Context.BIND_AUTO_CREATE);
        // 为id为settings_btn的按钮设置点击监听器
        findViewById(R.id.settings_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
                // 启动SettingsActivity
                startActivity(intent);
            }
        });


        // 为id为pubsub_test_btn的按钮设置点击监听器
        findViewById(R.id.pubsub_test_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, PubSubTestActivity.class);
                // 启动PubSubTestActivity
                startActivity(intent);
            }
        });
        // 为id为dev_demo_btn的按钮设置点击监听器
        findViewById(R.id.dev_demo_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 创建跳转到DevicesDemoActivity的Intent
                Intent intent = new Intent(MainActivity.this, DevicesDemoActivity.class);
                // 启动DevicesDemoActivity
                startActivity(intent);
            }
        });
    }

    // 订阅主题的方法
    void subscribeTopics() {
        try {
            // 通过mqttBinder订阅主题“/test”
            mqttBinder.subscribe("/test");
        } catch (MqttException e) {
            // 订阅过程中出现异常，打印异常堆栈信息
            e.printStackTrace();
        }
    }

    // 取消订阅主题的方法
    void unSubscribeTopics() {
        try {
            // 通过mqttBinder取消订阅主题“/test”
            mqttBinder.unSubscribe("/test");
        } catch (MqttException e) {
            // 取消订阅过程中出现异常，打印异常堆栈信息
            e.printStackTrace();
        }
    }

    // 当MQTT连接成功时调用
    @Override
    public void onConnectSuccess() {
        // 订阅主题
        subscribeTopics();
        // 更新连接状态显示为“已连接”
        connectState.setText("已连接");
    }

    // 当MQTT连接出错时调用
    @Override
    public void onConnectError(String error) {
        // 记录连接错误信息到日志
        Log.d(TAG, "onConnectError: " + error);
        // 更新连接状态显示为“未连接”
        connectState.setText("未连接");
    }

    // 当MQTT消息发布完成时调用
    @Override
    public void onDeliveryComplete() {
        // 记录消息发布成功的日志
        Log.d(TAG, "publish ok");
    }

    // 当接收到MQTT消息时调用
    @Override
    public void onMqttMessage(String topic, String message) {
        // 此处未处理接收到的消息，可根据需求添加处理逻辑
    }

    // 当Activity重新启动时调用
    @Override
    protected void onRestart() {
        super.onRestart();
        // 判断MqttService是否已连接
        if (mqttBinder.isConnected()) {
            // 已连接，更新连接状态显示为“已连接”并订阅主题
            connectState.setText("已连接");
            subscribeTopics();
        } else {
            // 未连接，更新连接状态显示为“未连接”
            connectState.setText("未连接");
        }
    }

    // 当Activity停止时调用
    @Override
    protected void onStop() {
        super.onStop();
        // 取消订阅主题
        unSubscribeTopics();
    }

    // 当Activity销毁时调用
    @Override
    protected void onDestroy() {
        // 解绑MqttService服务
        unbindService(connection);
        super.onDestroy();
    }
}



/*
package com.example.mqttclient;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import com.example.mqttclient.mqtt.MqttService;

import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

public class MainActivity extends AppCompatActivity {

    private TextView connectState;
    private String TAG = "MainActivity";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        connectState = findViewById(R.id.connect_state);
        connect();

    }
    private IMqttActionListener iMqttActionListener = new IMqttActionListener() {
        @Override
        public void onSuccess(IMqttToken arg0) {
            Log.i(TAG, "connect success");
        }
        @Override
        public void onFailure(IMqttToken arg0, Throwable arg1) {
            Log.i(TAG, "connect fail:" + arg1.toString());
        }
    };
    private MqttCallback mqttCallback = new MqttCallback() {
        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            Log.i(TAG, "messageArrived:" + new String(message.getPayload()));
        }
        @Override
        public void deliveryComplete(IMqttDeliveryToken arg0) {
            Log.i(TAG, "publish ok:" + arg0.toString());
        }
        @Override
        public void connectionLost(Throwable arg0) {
            Log.i(TAG, "connectionLost:" + arg0.toString());
        }
    };
    MqttAndroidClient client;
    MqttConnectOptions conOpt = new MqttConnectOptions();
    private void connect() {
        client = new MqttAndroidClient(this, "tcp://172.16.56.71", "clientId");
       */
/* client = new MqttAndroidClient(this, "tcp://172.19.229.124", "clientId");*//*

        client.setCallback(mqttCallback);// 设置MQTT监听并且接受消息
        conOpt.setCleanSession(true);// 清除缓存
        conOpt.setConnectionTimeout(10);// 设置超时时间，单位：秒
        conOpt.setKeepAliveInterval(20);// 心跳包发送间隔，单位：秒
        conOpt.setUserName("userName");
        conOpt.setPassword("password".toCharArray());
        try {
            if(!client.isConnected())
                client.connect(conOpt, null, iMqttActionListener);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }



}
*/
